<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        /* 
            滑动窗口-- 也是双指针
            时间复杂度：O(n)，并不是两个循环就是O(n)，每个元素至多进去一次，出来一次，就是O(n * 2) 也就是O(n)
            空间复杂度：O(1)
        */
        var totalFruit = function(fruits) {
            let start = 0
            let end = 0
            let len = fruits.length
            let ans = 0 
            let map = new Map() // 利用map记录每个数字出现的次数，
            while (end < len) {
                let rightVal = fruits[end]
                map.set(rightVal, map.get(rightVal) ? map.get(rightVal) + 1 : 1)
                // 如果水果种类超过了2个，则把left对应的值回退，
                while (map.size > 2) {
                    let startV = fruits[start]
                    map.set(startV, map.get(startV) - 1)
                    if (map.get(startV) === 0) {
                        // 如果该水果的次数为0，则删掉该种类的水果
                        map.delete(startV)
                    }
                    start++
                }
                ans = Math.max(ans, end - start + 1)
                end++
            }
            return ans
        };
        console.log(totalFruit([1,2,1]));
        // console.log(minSubArrayLen(4, [1, 4, 4]));
        // console.log(minSubArrayLen(11, [1, 1, 1, 1, 1, 1, 1, 1]));
        // console.log(minSubArrayLen(213, [12,28,83,4,25,26,25,2,25,25,25,12]));
        
    </script>
</body>
</html>